package com.flot.yazb.widget.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * json 与map像话转换工具类
 */
public class HashmapToJson {

    public static void main(String args[]){
        Map<String ,String> map = new HashMap();
        map.put("name", "12342");
        map.put("pass", "4355");
        map.put("jos", "999");
        map.put("wang", "999");
        HashmapToJson jsonType = new HashmapToJson();
//        String mm = jsonType.hashMapToJson(map);
        String mm = jsonType.simpleMapToJsonStr(map);
        System.out.println(mm);
//        Map mp = jsonType.getData(mm);
//        System.out.println(mp.get("wang"));

    }

    //map json
    public static String simpleMapToJsonStr(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return "null";
        }
        String jsonStr = "{";
        Set<?> keySet = map.keySet();
        for (Object key : keySet) {
            jsonStr += "\"" + key + "\":\"" + map.get(key) + "\",";
        }
        jsonStr = jsonStr.substring(0, jsonStr.length() - 2);
        jsonStr += "}";
        return jsonStr;
    }

    //map  -json
    public static String hashMapToJson(Map map) {
        String string = "{";
        for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
            Map.Entry e = (Map.Entry) it.next();
            string += "'" + e.getKey() + "':";
            string += "'" + e.getValue() + "',";
        }
        string = string.substring(0, string.lastIndexOf(","));
        string += "}";
        return string;
    }

    //json --map
    public Map  getData(String str){
        String sb = str.substring(1, str.length()-1);
        String[] name =  sb.split("\\\",\\\"");
        String[] nn =null;
        Map map = new HashMap();
        for(int i= 0;i<name.length; i++){
            nn = name[i].split("\\\":\\\"");
            map.put(nn[0], nn[1]);
        }
        return map;
    }
}